package _2025_4_26;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TCPEchoClient {
    //创建客服端
    Socket socket;
    String IP;
    int port;

    public TCPEchoClient(String IP, int port) throws IOException {
        if (IP == null || IP.isEmpty()) {
            throw new RuntimeException("IP不能为空");
        }
        if (port < 1024 || port > 65535) {
            throw new RuntimeException("端口号不符合要求");
        }
        socket = new Socket(IP, port);
    }

    public void start() {
        System.out.println("客服端已启动");

            try (InputStream inputStream = this.socket.getInputStream();
                 OutputStream outputStream = this.socket.getOutputStream()) {
                while (true) {
                    Scanner scanner = new Scanner(System.in);
                    String request = scanner.nextLine();
                    if (request.isEmpty() || request == null) {
                        System.out.println("发送内容不能为空");
                    }
                    PrintWriter printWriter = new PrintWriter(outputStream);
                    //把数据写入输出流
                    printWriter.println(request);
                    printWriter.flush();
                    //接收服务端发送来的数据
                    Scanner scan = new Scanner(inputStream);
                    String respose = scan.nextLine();
                    System.out.println("request:" + request + "repose" + respose);
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
                }

    public static void main(String[] args) throws IOException {
        TCPEchoClient tcpEchoClient=new TCPEchoClient("127.0.0.1",8888);
        tcpEchoClient.start();
    }
}


